-- AmazonLeaderboardM
-- Created by chengb Oct/22/2015
-- 亚马逊排行榜

module("AmazonLeaderboardM", package.seeall);

local PURE_FILE = "AmazonLeaderboardM";

-- Amazon排行榜配置表
local leaderboardTable = {};

-- 根据规则存放配置
local listByRule = {};

-- 所有子模块
local rules = {};

-- 分数提交队列
local scoreRequestQuene = {};

-- 请求处理间隔（秒）
local CHECK_INTERVAL = 1;

-- 内部函数声明
local appendSubmitRequest;
local checkSubmitRequest;

-- 载入配置表
local _init = false;
local loadCsv = function()
    if _init then return end
    _init = true;

    leaderboardTable = {};
    amazon_leaderboard_CSV = get_amazon_leaderboard_CSV();
    for i = 1, #amazon_leaderboard_CSV do
        local id = amazon_leaderboard_CSV[i].id;
        leaderboardTable[id] = amazon_leaderboard_CSV[i];

        -- 根据规则存放
        local rule = amazon_leaderboard_CSV[i].rule;
        if listByRule[rule] == nil then
            listByRule[rule] = {};
        end
        table.insert(listByRule[rule], id);
    end

    amazon_leaderboard_CSV = {};
end

-- 初始化
function init()
    if not isLeaderboardOpen() then
        return;
    end

    if not _init then
        loadCsv();

        -- 载入所有的规则处理子模块
        rules = LOAD_PATH("game/logic/module/amazon_leaderboard");
    end    
end

-- 功能是否开放
function isLeaderboardOpen()
    if PUBLISH_PLATFORM ~= PUBLISH_TYPE_AMAZON then
        return false;
    end

    return true;
end

-- 查询排行榜配置
function query(id, path)
    local m = leaderboardTable[id];

    if not m or path == "" or path == nil then
        return m;
    else
        return m[path];
    end
end

-- 根据字段检索id
function queryIdbyField(field, value)
    for id, info in pairs(leaderboardTable) do
        if info[field] == value then
            return id;
        end
    end
    return nil;
end

-- 根据规则获取成就id
function getIdsByRule(id)
    return listByRule[id] or {};
end

-- 能否提交分数
function canSubmitScore(id, score)
    local config = query(id);
    if not config then
        trace(PURE_FILE, "无法提交分数：不存在(id=%d)的排行榜配置。", id);
        return false;
    end

    local limitScore = config.limit_score;
    if score < limitScore then
        trace(PURE_FILE, "无法提交分数：分数没有达到上榜要求，需求(%d)，当前(%d)。", limitScore, score);
        return false;
    end

    return true;
end

-- 提交分数
function submitScore(id, score)
    if true ~= canSubmitScore(id, score) then
        return false;
    end

    if AmazonAchievementM.isRemindConnectAmazon() then
        -- 当前尚未登录亚马逊账号，抛出提醒事件
        AmazonAchievementM.remindConnectAmazon();
        return false;
    end

    trace(PURE_FILE, "尝试提交排行榜(%d)分数(%d)", id, score);

    local config = query(id);

    -- 获取Amazon上配置的排行榜编号
    local gid = config.gid;

    -- 将提交分数的请求投入到队列中
    appendSubmitRequest(gid, score);

    if not ScheduleM.isSchemeAlive("AmazonLeaderboardM") then
        ScheduleM.createScheme("AmazonLeaderboardM", checkSubmitRequest, CHECK_INTERVAL, true);
    end

    return true;
end

-- 将提交分数的请求投入到队列中
function appendSubmitRequest(gid, score)
    for i = 1, #scoreRequestQuene do
        local info = scoreRequestQuene[i];
        if info.gid == gid then
            if score <= info.score then
                -- 分数较上一次没有提升，本次请求无效
                return;
            end

            info.score = score;
            return;
        end
    end

    table.insert(scoreRequestQuene, {["gid"] = gid, ["score"] = score,});
end

-- 监测提交请求
function checkSubmitRequest()
    if #scoreRequestQuene == 0 then
        ScheduleM.deleteScheme("AmazonLeaderboardM");
        trace("AmazonLeaderboardM", "所有分数提交请求处理完毕。");
        return;
    end

    -- 处理队列中的第一条请求
    local info  = scoreRequestQuene[1];
    local gid   = info.gid;
    local score = info.score;

    trace(PURE_FILE, "处理分数提交请求：gid = %s, score = %d", gid, score);

    -- 调用sdk提交分数
    if AmazonAgent then
        AmazonAgent.submitAmazonLeaderboardScore(gid, score);
    end

    table.remove(scoreRequestQuene, 1);
end

-- 显示排行榜
function displayLeaderboard(id)
    local config = query(id);
    if not config then
        return false;
    end

    -- 获取GoolgePlay上配置的排行榜编号
    local gid = config.gid;

    -- 调用sdk显示排行榜
    if AmazonAgent then
        AmazonAgent.displayAmazonLeaderboard(gid);
    else
        alert(getLocStr("disable_function"));
    end

    return true;
end

-- 显示亚马逊排行榜列表
function displayAllAmazonLeaderboards()
    if AmazonAgent then
        AmazonAgent.displayAllAmazonLeaderboards();
    else
        alert(getLocStr("disable_function"));
    end
end





